import { defineStore } from "pinia";
import { ref, computed } from "vue";

// 初始状态
function initState() {
    return {
        // 产品ID（TODO:为后续多用户预留）
        productId: 1,
        // 贷款列表
        loans: null,
        // 申请数据
        applyData: {
            amount: null,
            period: null
        },
        // 选择的银行卡ID
        selectBankCardId: null,
        // 加载状态
        loading: false,
        // 是否已加载数据
        isLoaded: false
    };
}

export const useLoanStore = defineStore("loanStore", () => {
    // 状态
    const state = ref(initState());

    // 计算属性
    const loading = computed(() => state.value.loading);
    const isLoaded = computed(() => state.value.isLoaded);
    const hasLoans = computed(() => state.value.loans.length > 0);

    // 贷款列表缓存
    function setLoans(loans) {
        state.value.loans = loans;
        state.value.isLoaded = true;
    }

    // 设置数据
    function setApplyData(applyData) {
        state.value.applyData = applyData;
    }

    // 设置选择的银行卡ID
    function setSelectBankCardId(bankCardId) {
        state.value.selectBankCardId = bankCardId;
    }

    // 重置状态
    function resetState() {
        Object.assign(state.value, initState());
    }

    return {
        state,
        loading,
        isLoaded,
        hasLoans,
        setSelectBankCardId,
        setApplyData,
        setLoans,
        resetState
    };
}, {
    persist: {
        key: 'loan-store',
        storage: localStorage,
        paths: ['state.loans', 'state.isLoaded', 'state.applyData']
    }
});